import {StyleSheet, Text, TouchableOpacity, View, FlatList} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import NoData from "@/components/NoData";
import {Toast} from "@ant-design/react-native";
import {useDispatch} from "react-redux";
import {router, useLocalSearchParams} from "expo-router";
import {set_rowData} from "@/store/reducer/contentManage/contentManageSlice";

import {
  useGetListQuery,
  useAssignAccountMutation,
  useDeleteBatchMutation
} from "@/store/api/contentManage/contentManageApi";

type Props = {}

const batch = (props: Props) => {
  const [list,setList] = useState<any>([])
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
  })
  const [titleType,setTitleType] = useState<any>('')
  const [count,setCount] = useState<any>(0)
  const [deleteOpen, setDeleteOpen] = useState(false)
  
  const {data:listDataRef1,isSuccess:listSuccess1,refetch:listRefetch} = useGetListQuery(listParams)

  const [assignAccountFun] = useAssignAccountMutation()
  const [deleteBatchFun] = useDeleteBatchMutation()

  const dispatch = useDispatch()
  const {type} = useLocalSearchParams()
  
  useEffect(() => {
    setTitleType(type)
    if(listDataRef1?.code === 200){
      const list = listDataRef1?.result.records || []
      setList(list)
    }
  },[type, listSuccess1,listDataRef1])

  //选择文案
  const handleCheckChange = (index:any) => {
    let arr = JSON.parse(JSON.stringify(list))
    arr[index].checked = !arr[index].checked
    setList(arr)

    let count = arr.filter((val:any) => val.checked).length
    setCount(count)
  }

  const handleSubmit = () => {
    if(count == 0) return

    let arr = list.filter((val:any) => val.checked).map((val:any) => val.id)
    
    if(titleType == 'account'){
      assignAccountFun({ids: arr.join()}).then(res => {
        if (res.data.code === 200) {
          Toast.info('分配成功')
          listRefetch()
          dispatch(set_rowData({}))
          router.back()
        }
      })
    }else{
      deleteBatchFun({ids: arr.join()}).then(res => {
        if (res.data.code === 200) {
          Toast.info('删除成功')
          listRefetch()
          dispatch(set_rowData({}))
          router.back()
        }
      })
    }
  }

  return (
    <PageScrollView
      isTransparentTab
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={titleType == 'account' ? '随机分配账号' : '批量删除'}
        />
      }
      pageBottom = {
        <View style={styles.page_bottom}>
          <Text style={{color: 'rgba(0, 0, 0, 0.3)'}}>已选{ count }个</Text>
          <FcButton
            onClick={() => titleType == 'account' ? handleSubmit() : setDeleteOpen(true)}
            type='BjJB'
            colors={count != 0 ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: '48%', height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName={titleType == 'account' ? '确认分配' : '删除'}
          />
        </View>
      }
    >
      <View>
        <FlatList
          data={list}
          renderItem={({item,index}) => (
            <View style={styles.list_item}>
              <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active]} onPress={() => {handleCheckChange(index)}}>
                {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
              </TouchableOpacity>
              <View style={{flex: 1, display: 'flex', flexDirection: 'row'}}>
                <Text style={styles.list_item_title} numberOfLines={2}>{ item?.content.split(/【标题】[:：]?/)[1]?.split(/【正文】[:：]?/)[0]?.replace(/[\r\n]+/g, '') || item.content}</Text>
                <Text style={[styles.list_item_status, item.pubStatus == 1 ? {backgroundColor: 'rgba(7, 193, 96, 0.1)', color: '#07C160'} : item.pubStatus == 2 ? {backgroundColor: 'rgba(250, 81, 81, 0.1)', color: '#FA5151'} : null]}>{ !item.pubStatus ? '未发布' : item.pubStatus == 1 ? '已发布' : item.item.pubStatus == 2 ? '发布失败' : '' }</Text>
              </View>
            </View>
          )}
          keyExtractor={(_, index) => `list_item${index}`}
        />
        {!list && <NoData hintText='目前没有数据，AI正在获取，请等待！再次点击关键词刷新获取列表。'/>}

        {/* 删除弹窗 */}
        <FcModal
          isOpen={deleteOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setDeleteOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={'确认要删除吗？'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setDeleteOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleSubmit(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前内容将被删除哦~</Text>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default batch

const styles = StyleSheet.create({
  page_bottom: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 56,
    paddingHorizontal: 16,
    backgroundColor: '#FFF',
  },
  select_icon: {
    width: 20,
    height: 20,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    marginRight: 12,
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
  list_item: {
    padding: 12,
    borderRadius: 8,
    marginBottom: 8,
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFF',
  },
  list_item_title: {
    flex: 1,
    fontSize: 17, 
    lineHeight: 26,
    marginRight: 12,
    fontWeight: '400',
  },
  list_item_status: {
    height: 22,
    fontSize: 12,
    marginTop: 3,
    lineHeight: 22,
    borderRadius: 4,
    paddingHorizontal: 6,
    color: 'rgba(0, 0, 0, 0.5)',
    backgroundColor: 'rgba(0, 0, 0, 0.06)',
  },
})